<template>
  <div class="absolute w-full h-full bottom-0 left-0 flex items-center justify-center">

    <div class="absolute w-full bottom-0 flex items-center justify-around px-4">
      <div class="w-1/4 h-80">
        <v-chart class="chart" :option="option1" autoresize />
      </div>
      <div class="w-1/4 h-80">
        <v-chart class="chart" :option="option2" autoresize />
      </div>
      <div class="w-1/4 h-80">
        <v-chart class="chart" :option="option3" autoresize />
      </div>
    </div>
  </div>
</template>

<script setup>
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { graphic } from 'echarts'
import VChart from 'vue-echarts'
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { getChartData } from '@/api/api'

use([CanvasRenderer, LineChart, TooltipComponent, GridComponent, LegendComponent])

// 时间标签将从接口数据中动态生成
const timeLabels = ref([])

// 公共坐标与网格样式（深蓝背景适配）
const baseAxes = computed(() => ({
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      if (params && params.length > 0) {
        const timestamp = params[0].axisValue
        // 将ISO格式时间戳转换为 YYYY-MM-DD HH:mm:ss 格式
        const date = new Date(timestamp)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        const timeStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`

        let result = `<div style="margin-bottom: 5px; font-weight: bold;">${timeStr}</div>`
        params.forEach((param) => {
          result += `<div style="margin: 2px 0;">
            <span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
            ${param.seriesName}: ${param.value}
          </div>`
        })
        return result
      }
      return ''
    },
  },
  grid: { left: '13%', top: '12%', right: '3%', bottom: '5%', containLabel: true },
  xAxis: {
    type: 'category',
    data: timeLabels.value,
    boundaryGap: true,
    axisTick: { show: false },
    axisLabel: {
      interval: 0,
      rotate: -35,
      overflow: 'truncate',
      width: 50,
      hideOverlap: true,
      formatter: (value) => {
        // 格式化时间戳显示
        if (value) {
          const date = new Date(value)
          const hh = String(date.getHours()).padStart(2, '0')
          const mm = String(date.getMinutes()).padStart(2, '0')
          return `${hh}:${mm}`
        }
        return value
      },
      textStyle: { show: true, color: '#ffffff', fontSize: 12 },
    },
    axisLine: {
      symbol: ['none', 'arrow'],
      symbolSize: [10, 15],
      symbolOffset: [0, 0],
      lineStyle: { width: 2, color: 'rgba(255,255,255,0.6)' },
    },
  },
}))

const buildYAxis = (name) => ({
  name,
  nameTextStyle: { color: '#ffffff', padding: [0, 0, 6, 0] },
  type: 'value',
  splitLine: { show: true, lineStyle: { color: 'rgba(255,255,255,0.2)' } },
  axisLine: {
    show: true,
    symbol: ['none', 'arrow'],
    symbolSize: [10, 15],
    symbolOffset: [0, 0],
    lineStyle: { width: 2, color: 'rgba(255,255,255,0.6)' },
  },
  axisLabel: { textStyle: { show: true, color: '#ffffff', fontSize: 12 } },
})

const buildLine = (name, data, color, withArea = true) => ({
  name,
  type: 'line',
  data,
  smooth: true,
  symbol: 'circle',
  symbolSize: 0,
  lineStyle: { width: 2, type: 'solid', color },
  itemStyle: { borderWidth: 5, borderColor: color, color },
  areaStyle: withArea
    ? {
        color: new graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: `${color}CC` },
          { offset: 1, color: `${color}1A` },
        ]),
      }
    : undefined,
})

// 图表数据管理
const chartDataMap = ref({})
const len = computed(() => timeLabels.value.length)

// 需要请求的asset_alias列表
const assetAliases = [
  '/1880/RMC/L2/ACT/R2_P1/Temp_Ext', // 出口温度2-1
  '/1880/RMC/L2/ACT/R2_P3/Temp_Ext', // 出口温度2-3
  '/1880/RMC/L2/ACT/R2_P5/Temp_Ext', // 出口温度2-5
  '/1880/RMC/L2/ACT/R2_P1/CenterlineDev', // 带钢偏差2-1
  '/1880/RMC/L2/ACT/R2_P3/CenterlineDev', // 带钢偏差2-3
  '/1880/RMC/L2/ACT/R2_P5/CenterlineDev', // 带钢偏差2-5
  '/1880/RMC/L2/ACT/R2_P1/Width', // 带钢宽度2-1
  '/1880/RMC/L2/ACT/R2_P3/Width', // 带钢宽度2-3
  '/1880/RMC/L2/ACT/R2_P5/Width', // 带钢宽度2-5
]

// 获取图表数据
const fetchChartData = async () => {
  try {
    const newDataMap = {}
    const allTimestamps = new Set()

    // 按asset_alias分组数据
    assetAliases.forEach((alias) => {
      newDataMap[alias] = []
    })

    // 为每个asset_alias单独发送请求
    const requests = assetAliases.map(async (alias) => {
      try {
        const res = await getChartData({ asset_alias: alias })
        if (res && Array.isArray(res.data)) {
          res.data.forEach((item) => {
            if (newDataMap[item.asset_alias]) {
              newDataMap[item.asset_alias].push({
                timestamp: item.timestamp,
                value: item.value,
              })
              allTimestamps.add(item.timestamp)
            }
          })
        }
      } catch (error) {
        console.error(`Error fetching data for ${alias}:`, error)
      }
    })

    // 等待所有请求完成
    await Promise.all(requests)

    // 生成时间标签（按时间排序）
    timeLabels.value = Array.from(allTimestamps).sort()

    // 为每个asset_alias生成时间序列数据
    assetAliases.forEach((alias) => {
      const dataPoints = newDataMap[alias] || []
      const timeSeriesData = []

      // 为每个时间点生成数据
      timeLabels.value.forEach((timestamp) => {
        const dataPoint = dataPoints.find((dp) => dp.timestamp === timestamp)
        timeSeriesData.push(dataPoint ? dataPoint.value : 0)
      })

      chartDataMap.value[alias] = timeSeriesData
    })
  } catch (e) {
    console.error('getChartData error:', e)
  }
}

// 生成空数据数组的函数
const genEmpty = () => Array.from({ length: len.value }, () => 0)

// 1. 出口温度2-1、2-3、2-5
const option1 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('出口温度'),
  legend: { show: true, textStyle: { color: '#ffffff' } },
  series: [
    buildLine(
      '出口温度2-1',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P1/Temp_Ext'] || genEmpty(),
      '#1AC9FF',
    ),
    buildLine(
      '出口温度2-3',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P3/Temp_Ext'] || genEmpty(),
      '#FFD166',
    ),
    buildLine(
      '出口温度2-5',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P5/Temp_Ext'] || genEmpty(),
      '#4ECDC4',
    ),
  ],
}))

// 2. 带钢偏差2-1、2-3、2-5
const option2 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('带钢偏差'),
  legend: { show: true, textStyle: { color: '#ffffff' } },
  series: [
    buildLine(
      '带钢偏差2-1',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P1/CenterlineDev'] || genEmpty(),
      '#A29BFE',
    ),
    buildLine(
      '带钢偏差2-3',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P3/CenterlineDev'] || genEmpty(),
      '#06D6A0',
    ),
    buildLine(
      '带钢偏差2-5',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P5/CenterlineDev'] || genEmpty(),
      '#EF476F',
    ),
  ],
}))

// 3. 带钢宽度2-1、2-3、2-5
const option3 = computed(() => ({
  ...baseAxes.value,
  yAxis: buildYAxis('带钢宽度'),
  legend: { show: true, textStyle: { color: '#ffffff' } },
  series: [
    buildLine(
      '带钢宽度2-1',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P1/Width'] || genEmpty(),
      '#FF9F1C',
    ),
    buildLine(
      '带钢宽度2-3',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P3/Width'] || genEmpty(),
      '#118AB2',
    ),
    buildLine(
      '带钢宽度2-5',
      chartDataMap.value['/1880/RMC/L2/ACT/R2_P5/Width'] || genEmpty(),
      '#F72585',
    ),
  ],
}))

let chartTimer = null

onMounted(() => {
  fetchChartData()
  chartTimer = setInterval(fetchChartData, 10000)
})

onUnmounted(() => {
  if (chartTimer) clearInterval(chartTimer)
})
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
